﻿CREATE PROCEDURE [audit].[StopTrace]
@Trace SQL_VARIANT, @TracePath NVARCHAR (512)=NULL OUTPUT, @TraceID INT=NULL OUTPUT
AS
BEGIN
	SET NOCOUNT ON

	DECLARE @RC int, @ERROR int
	SET @RC = 0
	SET @ERROR = 0

	EXEC @RC = audit.GetTraceInfo @Trace, @TraceID OUTPUT, @TracePath OUTPUT
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	IF(@TraceID IS NULL)
		GOTO EXIT_PROC

	PRINT 'Stopping trace...'

	EXEC @RC = master.dbo.sp_trace_setstatus @TraceID, 0 --STOP TRACE FLAG
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	EXEC @RC = master.dbo.sp_trace_setstatus @TraceID, 2 --CLOSE TRACE FLAG
	SET @ERROR = @@ERROR
	IF(@ERROR <> 0)
	OR(@RC <> 0)
		GOTO ERROR_HANDLER

	PRINT 'Trace stopped successfully'
	GOTO EXIT_PROC

ERROR_HANDLER:
	DECLARE @ERROR_MESSAGE nvarchar(255)
	IF(@RC <> 0)
		BEGIN
			SET @ERROR_MESSAGE = audit.GetTraceReturnCodeValue(@RC)
			RAISERROR(@ERROR_MESSAGE,16,1)
		END
	ELSE
		SET @RC = @ERROR

	RAISERROR('Failed to stop trace',16,1)
	
EXIT_PROC:
	RETURN(@RC)
END